package com.ms.p2p.service;



import com.ms.common.utils.AppContext;
import com.ms.common.utils.RSAUtils;
import com.ms.common.utils.SpringContextHolder;
import com.ms.p2p.utils.TradeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.UUID;

@Service
public class AppRSAService {
	private static final String privateKey = "MS_V_1_0";



	private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);

	public RSAPublicKey generateKey() {

		KeyPair keypair = RSAUtils.generateKeyPair();

		RSAPublicKey rsapublickey = (RSAPublicKey)keypair.getPublic();

		RSAPrivateKey rsaprivatekey = (RSAPrivateKey)keypair.getPrivate();
		String key = UUID.randomUUID().toString();
       	Cache cache = cacheManager.getCache("mobileRSA");
		cache.put(key,rsaprivatekey);
		//httpsession.setAttribute(key, rsaprivatekey);
		HashMap map = new HashMap();
		map.put("token",key);
		map.put("rsapublickey",rsapublickey);
		return rsapublickey;
	}
	public void removePrivateKey(HttpServletRequest request) {
		Assert.notNull(request);
		HttpSession httpsession = request.getSession();
		httpsession.removeAttribute(privateKey);
	}

	public String decryptParameter(String name,String token) {
		HttpServletRequest request = AppContext.getRequest();
		Assert.notNull(request);
		if (name != null) {
			HttpSession httpsession = request.getSession();
			RSAPrivateKey rsaprivatekey = (RSAPrivateKey)httpsession.getAttribute(privateKey);
			if (rsaprivatekey != null && StringUtils.isNotEmpty(name)){
				return RSAUtils.decrypt(rsaprivatekey, name);
			}
		}
		return null;
	}

	public String entryParameter(String name,RSAPublicKey rsapublickey) {
		HttpServletRequest request = AppContext.getRequest();
		Assert.notNull(request);
		if (name != null) {
			return RSAUtils.encrypt(rsapublickey, name);


		}
		return null;
	}

}
